package com.simple.editor.action.impl;

import com.simple.editor.ApplicationContext;
import com.simple.editor.callback.Callback;
import com.simple.editor.action.EditorException;
import com.simple.editor.callback.DefaultUICallbackImpl;
import com.simple.editor.converter.FileModelConverter;
import com.simple.editor.ui.FileModel;
import com.simple.editor.ui.InfoPane;
import com.simple.editor.vcs.VcsClient;
import com.simple.editor.vcs.VcsClientRegistry;
import com.simple.editor.vcs.VcsFile;

import java.util.Map;

/**
 * {@link CommitEditorUIAction} handles user "Commit File" action.
 * <p/>
 * Created with IntelliJ IDEA.
 * User: vsoroka
 * Date: 07.06.13
 * Time: 12:40
 * To change this template use File | Settings | File Templates.
 */
public class CommitEditorUIAction extends AbstracEditorUIAction {

    private final ApplicationContext ctx;
    private final InfoPane infoPane;
    private final VcsClientRegistry vcsClientRegistry;

    public CommitEditorUIAction(final ApplicationContext ctx, final InfoPane infoPane, final VcsClientRegistry vcsClientRegistry) {
        this.ctx = ctx;
        this.infoPane = infoPane;
        this.vcsClientRegistry = vcsClientRegistry;
    }

    @Override
    public void perform(final FileModel... files) throws EditorException {
        perform(new DefaultUICallbackImpl(), files);
    }

    @Override
    public void perform(final Callback uiCallback, final FileModel... files) throws EditorException {
        if (files != null && files.length > 0) {

            final VcsClient vcsClient = vcsClientRegistry.getCurrentVcsClient();

            final Map<String, VcsFile> vcsFilesMap = FileModelConverter.convertFiles(files);

            // Notify about action start event
            uiCallback.onStart();

            vcsClient.commit(new DefaultUICallbackImpl("Committing files", infoPane), vcsFilesMap.values());

            // Refresh file status
            vcsClient.refreshStatus(new RefreshActionUICallbackImpl(vcsFilesMap, infoPane, ctx, files) {

                @Override
                public void onComplete() {
                    super.onComplete();
                    uiCallback.onComplete();
                }

                @Override
                public void onFailure(Exception ex) {
                    super.onFailure(ex);
                    uiCallback.onFailure(ex);
                }
            }, vcsFilesMap.values());
        }
    }
}